package com.twotiger.and.activity.current;

import java.util.HashMap;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import app.twotiger.p2p.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.twotiger.and.Constants;
import com.twotiger.and.TwoTigerApp;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.base.BaseFragment;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.ConstantDataUnit;
import com.twotiger.and.bean.CurrentProject;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.TimeUtils;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.ViewUtils;
import com.umeng.analytics.MobclickAgent;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshScrollView;

public class CurrentPage extends BaseFragment {

    private static final int GETCURRENTPROJECTSUCCES = 0;
    private static final int GETCURRENTPROJECTFAIL = 1;
    private static final int OPENAUTOCURRENTPROJECTSUCCES = 2;
    private static final int OPENAUTOCURRENTPROJECTFAIL = 3;
    private final static int OPEN_PAYMENT_SUCESS = 6;
    private final static int OPEN_PAYMENT_FAIL = 7;

    private HashMap<String, String> params;
    private BaseHandler handler;
    private CurrentProject mCurrentProject;

    private View view;
    private RelativeLayout rl_current_detail;
    private Button btn_2, btn_1;
    private PullToRefreshScrollView current_sc;
    private TextView tv_compound_yield, tv_interest_units, tv_boutique_msg, tv_in_amount,
            tv_partin_num, tv_invest_amount;
    private ImageView iv_can_enter, iv_active;
    private BitmapUtils bitmapUtils;
    private RelativeLayout rl_compound;

    @Override
    protected View loadViewLayout(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.current_page_layout, null);
        return view;
    }

    @Override
    protected void findViewById(View view) {
        rl_current_detail = (RelativeLayout) view.findViewById(R.id.rl_current_detail);
        btn_2 = (Button) view.findViewById(R.id.btn_2);
        btn_1 = (Button) view.findViewById(R.id.btn_1);
        tv_compound_yield = (TextView) view.findViewById(R.id.tv_compound_yield);
        iv_active = (ImageView) view.findViewById(R.id.iv_active);
        tv_interest_units = (TextView) view.findViewById(R.id.tv_interest_units);
        tv_boutique_msg = (TextView) view.findViewById(R.id.tv_boutique_msg);
        tv_in_amount = (TextView) view.findViewById(R.id.tv_in_amount);
        tv_invest_amount = (TextView) view.findViewById(R.id.tv_invest_amount);
        tv_partin_num = (TextView) view.findViewById(R.id.tv_partin_num);
        iv_can_enter = (ImageView) view.findViewById(R.id.iv_can_enter);
        rl_compound = (RelativeLayout) view.findViewById(R.id.rl_compound);

        current_sc = (PullToRefreshScrollView) view.findViewById(R.id.current_sc);
        View fl_inner = current_sc.findViewById(R.id.fl_inner);
        fl_inner.setBackgroundColor(getResources().getColor(app.twotiger.p2p.R.color.bg_1));

    }

    /**
     * 判断是否登录
     * 
     * @return
     */
    protected boolean isLogin() {
        if (!TextUtils.isEmpty(TwoTigerApp.getInstance().getUser().token)) {
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.iv_active: //活期活动
            if (!isLogin()) {
                Intent intent = new Intent(mactivity, LoginPage.class).putExtra("FROM",
                    R.id.to_inverst);
                startnewActivity(intent, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
                return;
            }
            if (mCurrentProject == null) {
                getCurrentProject();
                return;
            }
            if (!TwoTigerApp.getInstance().getUser().hasOpenThirdAct) {
                PromptManager.showConfirmAlertCommon(mactivity, 0, "",
                    "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {

                        }

                        @Override
                        public void onClickCancel() {
                            // 确认，则继续
                            params.clear();
                            params.put("token", getToken());
                            mactivity.getDate(params, Constants.REGISTHF, handler,
                                OPEN_PAYMENT_SUCESS, OPEN_PAYMENT_FAIL, true, true, false);
                        }
                    });

                return;
            }
            MobclickAgent.onEvent(mactivity, Constants.UMENG_EVENT_CURRENT_PAGECLICK);
            Intent in1 = new Intent(mactivity, WebViewPage.class);
            in1.putExtra("title", "活期刮刮卡");
            in1.putExtra("url", mCurrentProject.getActivityUrl());
            in1.putExtra("BACK_MODE", WebViewPage.BACK_DIRECT);
            mactivity.startNewActivity(in1, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.rl_current_detail: // 查看详情
            ConstantDataUnit hqjs = mactivity.getConstantDataByKey(Constants.dz_hqjs);
            if (hqjs != null) {
                Intent in = new Intent(mactivity, WebViewPage.class);
                in.putExtra("title", hqjs.getName());
                in.putExtra("url", hqjs.getVal());
                in.putExtra("TIGER_HOST", CurrentHost.TIGER_HOST);
                mactivity.startNewActivityforresult(in, R.anim.push_left_in, R.anim.push_left_out, CurrentHost.CURRENTREQUEST);
            }
            break;
        case R.id.btn_1: //转出
            if (!isLogin()) {
                Intent intent = new Intent(mactivity, LoginPage.class).putExtra("FROM",
                    R.id.to_inverst);
                startnewActivity(intent, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
                return;
            }
            if (!TwoTigerApp.getInstance().getUser().hasOpenThirdAct) {
                PromptManager.showConfirmAlertCommon(mactivity, 0, "",
                    "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {

                        }

                        @Override
                        public void onClickCancel() {
                            // 确认，则继续
                            params.clear();
                            params.put("token", getToken());
                            mactivity.getDate(params, Constants.REGISTHF, handler,
                                OPEN_PAYMENT_SUCESS, OPEN_PAYMENT_FAIL, true, true, false);
                        }
                    });

                return;
            }
            if (TwoTigerApp.getInstance().getUser().hasOpenProjectXAct) {
                Intent intent2 = new Intent(mactivity, CurrentInputAmountOutPage.class);
                startnewActivity(intent2, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
            } else {
                PromptManager.showCurrentAlertHasBtn(mactivity, "",
                    "参与老虎活期，需要您授权开通账户自动投资功能。\n自动投资将仅用于活期每日复投，不会影响到其他资金。", "立即开通", false,
                    new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {
                            openAutoCurrentProject();
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
            }
            break;
        case R.id.btn_2: //立即转入

            if (!isLogin()) {
                Intent intent = new Intent(mactivity, LoginPage.class).putExtra("FROM",
                    R.id.to_inverst);
                startnewActivity(intent, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
                return;
            }
            if (mCurrentProject == null) {
                getCurrentProject();
                return;
            }
            if (!TwoTigerApp.getInstance().getUser().hasOpenThirdAct) {
                PromptManager.showConfirmAlertCommon(mactivity, 0, "",
                    "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {

                        }

                        @Override
                        public void onClickCancel() {
                            // 确认，则继续
                            params.clear();
                            params.put("token", getToken());
                            mactivity.getDate(params, Constants.REGISTHF, handler,
                                OPEN_PAYMENT_SUCESS, OPEN_PAYMENT_FAIL, true, true, false);
                        }
                    });

                return;
            }
            if (TwoTigerApp.getInstance().getUser().hasOpenProjectXAct) {
                Intent intent2 = new Intent(mactivity, CurrentInputAmountPage.class);
                intent2.putExtra("CURRENTPROJECT", mCurrentProject);
                mactivity.startNewActivityforresult(intent2, R.anim.slide_in_from_bottom,
                    R.anim.silent_anim, CurrentHost.CURRENTREQUEST);
            } else {
                PromptManager.showCurrentAlertHasBtn(mactivity, "",
                    "参与老虎活期，需要您授权开通账户自动投资功能。\n自动投资将仅用于活期每日复投，不会影响到其他资金。", "立即开通", false,
                    new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {
                            openAutoCurrentProject();
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
            }
            break;
        case R.id.iv_can_enter:

            if (mCurrentProject == null) {
                getCurrentProject();
                return;
            }
            PromptManager.showCurrentAlert(
                mactivity,
                "可转金额",
                "老虎活期每人限制持有" + ArithUtils.coverMoney(mCurrentProject.getMaxInAmount() + "")
                        + "元\n您当前持有："
                        + ArithUtils.coverMoney(mCurrentProject.getIningAmount() + "") + "元\n可转金额："
                        + ArithUtils.coverMoney(mCurrentProject.getInAmount() + "") + "元");
            break;
        case R.id.rl_compound:
            if (mCurrentProject == null) {
                getCurrentProject();
                return;
            }
            PromptManager.showCurrentAlert(
                mactivity,
                "复合年利率",
                "复合年利率是指收益复投后的年化收益，老虎活期采用收益复投的方式，所以复合年利率会高于基础年利率。\n基础年利率："
                        + ArithUtils.coverMoney(mCurrentProject.getYield() + "") + "%\n基础万元日收益："
                        + ArithUtils.coverMoneyFour(mCurrentProject.getInterestUnits() + "") + "元");
            break;
        default:
            break;
        }
    }

    private ConstantDataUnit getConstantDataByKey(String dzHqjs) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) { //从显示切换到不显示
            if (current_sc != null) {
                current_sc.scrollToTop();
            }
        } else {
            if (current_sc != null) {
                current_sc.scrollToTop();
            }
            getCurrentProject();
        }
        super.onHiddenChanged(hidden);
    }

    private void getCurrentProject() {
        params.clear();
        params.put("token", getToken());
        mactivity.getDate(params, Constants.PROJECTXQUERY, handler, GETCURRENTPROJECTSUCCES,
            GETCURRENTPROJECTFAIL, false, false, false);
    }

    private void openAutoCurrentProject() {
        params.clear();
        params.put("token", getToken());
        mactivity.getDate(params, Constants.PROJECTXOPEN, handler, OPENAUTOCURRENTPROJECTSUCCES,
            OPENAUTOCURRENTPROJECTFAIL, true, false, false);
    }

    /**
     * 获取token
     * @return
     */

    public String getToken() {
        return TwoTigerApp.getInstance().getUser().token;
    }

    @Override
    protected void setListener() {
        handler = new BaseHandler(mactivity) {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case OPEN_PAYMENT_SUCESS:
                    Basebean result_open = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_open.isOk()) {
                        Intent in = new Intent();
                        BroswerUrl responseinfo = JSON.parseObject(result_open.data,
                            BroswerUrl.class);
                        in.setClass(mactivity, WebViewPage.class).putExtra("title", "汇付天下托管账号")
                            .putExtra("url", responseinfo.getUrl())
                            .putExtra("BUSINESS_TYPE", WebViewPage.TYPE_PAYMENT_REGIST);
                        startnewActivity(in, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                    break;
                case OPEN_PAYMENT_FAIL:
                    showToast("网络不佳，请重试");
                    break;
                case GETCURRENTPROJECTSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        current_sc.getLoadingLayoutProxy().setLastUpdatedLabel(
                            "最后更新：今天 " + TimeUtils.getFormatDate(" HH:mm"));
                        mCurrentProject = JSONObject.parseObject((String) result.data,
                            CurrentProject.class);
                        fillData();
                    } else {
                        showToast(result.codeDesc);
                    }
                    current_sc.onRefreshComplete();
                    break;
                case GETCURRENTPROJECTFAIL:
                    showToast("网络不佳，请重试");
                    current_sc.onRefreshComplete();
                    break;
                case OPENAUTOCURRENTPROJECTSUCCES:
                    Basebean result_o = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_o.isOk()) {
                        BroswerUrl url = JSONObject.parseObject(result_o.data, BroswerUrl.class);
                        Intent intent = new Intent(mactivity, WebViewPage.class);
                        intent.putExtra("title", "账户自动投资");
                        intent.putExtra("url", url.getUrl());
                        intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_OPEN_AUTO_PROJECT);
                        startnewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(result_o.codeDesc);
                    }
                    break;
                case OPENAUTOCURRENTPROJECTFAIL:
                    showToast("网络不佳，请重试");
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }

        };
        current_sc.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getCurrentProject();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            }
        });
        rl_current_detail.setOnClickListener(this);
        btn_2.setOnClickListener(this);
        btn_1.setOnClickListener(this);
        iv_can_enter.setOnClickListener(this);
        rl_compound.setOnClickListener(this);
        iv_active.setOnClickListener(this);
    }

    private void fillData() {

        tv_compound_yield.setText(ArithUtils.coverMoney(mCurrentProject.getCompoundYield() + ""));
        tv_interest_units
            .setText(ArithUtils.coverMoneyFour(mCurrentProject.getInterestUnits() + ""));
        tv_boutique_msg.setText(mCurrentProject.getxBoutiqueMsg());
        tv_in_amount.setText(ArithUtils.coverMoneyComma(mCurrentProject.getInAmount() + ""));
        tv_invest_amount.setText(ArithUtils.coverMoneyComma(Double.parseDouble(mCurrentProject
            .getInvestAmount()) / 10000 + ""));
        tv_partin_num.setText(mCurrentProject.getPartInNum() + "");
        if ("1".equals(mCurrentProject.getActivityMark())) {
            iv_active.setVisibility(View.VISIBLE);
            bitmapUtils.display(iv_active, Constants.HOST + mCurrentProject.getActivityIcon(), new BitmapLoadCallBack<View>() {

                @Override
                public void onLoadCompleted(View arg0, String arg1, Bitmap arg2,
                                            BitmapDisplayConfig arg3, BitmapLoadFrom arg4) {
                    Bitmap bit = zoomImg(arg2, ViewUtils.dip2px(mactivity, 90));
                    iv_active.setImageBitmap(bit);
                }

                @Override
                public void onLoadFailed(View arg0, String arg1, Drawable arg2) {
                    
                }
            });
        } else {
            iv_active.setVisibility(View.GONE);
        }
    }
    
    /**
     * 等比例缩放图片
     * 
     * @param bm
     * @param newWidth
     * @return
     */
    public static Bitmap zoomImg(Bitmap bm, int newWidth ){
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = scaleWidth;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
         return newbm;
     }

    @Override
    protected void processLogic() {

        bitmapUtils = new BitmapUtils(mactivity);
        params = mactivity.getParm();
        getCurrentProject();
    }

    @Override
    public boolean isNeedLogin() {
        return false;
    }

    @Override
    public String getTitle() {
        return "老虎活期";
    }

    @Override
    public void rebuildTitleStyle() {
        subTitle.setBgResource(R.drawable.bg_account_title).setTitle(getTitle()).setLeftName("")
            .setRightName("").setColor(Color.WHITE).hideBtns().hideBottomLine();
        mactivity.tintManager.setTintResource(R.drawable.bg_account_statusbar);
        mactivity.setLayoutPadding(false);
    }

    @Override
    public void reLoadData() {

    }

}
